function [xm,xmnan,dm] = bettermonthavg(x,d)
%bettermontavg Function to get the average value in the month controlling for NAs
   %   Detailed explanation goes here
lowd = datevec(min(d));
highd =datevec(max(d));
dm = datenum(sort(repmat(lowd(1):highd(1),1,12))',repmat((1:12)',length(lowd(1):highd(1)),1),1);

%stopdate = datenum(year(max(d)),month(max(d)),1);  %broken because year is
%part of fin toolbox. 
stopdate = datenum(highd(1), highd(2),1);

ix = find(dm == stopdate);
dm = dm(1:ix); 
ndm = length(dm);
[~,nvars] = size(x);
xm = zeros(ndm,nvars);
xmnan = zeros(ndm,nvars);
for zx = 1:nvars;
    for zy = 1:ndm-1;
        xtemp = x(and(d<dm(zy+1),d>=dm(zy)),zx);
        xm(zy,zx)      =  mean(xtemp);
        xmnan(zy,zx)   = mean(xtemp(~isnan(xtemp)));
    end
    zy = ndm;
        xtemp = x(d>=dm(zy),zx);
        xm(zy,zx)      =  mean(xtemp);
        xmnan(zy,zx)   = mean(xtemp(~isnan(xtemp)));

end


end

